<template lang="pug">
	.face-detection-wrap
		canvas.canvas(id='myCanvas' canvas-id='myCanvas' :disable-scroll="true")
		camera.camera(device-position="front" flash="auto" :binderror="openError" v-if="showCamera")
			cover-view.detection-border
		.camera-tools
			.title 请将正脸置于取景框内
			.tips
				.main 温馨提示
				.sub 请保持正对手机，光线明亮、均匀
			.camera-btn(@click="next") {{buttonText}}

</template>

<script>
export default {
	name: 'faceDetection',
	data() {
		return {
			rpxR: '',
			clientHeight: '',
			clientWidth: '',
			faceBase64: '',
			buttonText: '点击拍照',
			showCamera: true,
			photoToken: '' //人脸令牌
		}
	},
	created() {
		let that = this
		this.wx.getSystemInfo({
			success: function(res) {
				let clientHeight = res.windowHeight,
					clientWidth = res.windowWidth,
					rpxR = 750 / clientWidth
				that.rpxR = rpxR
				that.clientHeight = clientHeight
				that.clientWidth = clientWidth
			}
		})
	},
	mounted() {
		this.familyRole = this.wx.getStorageSync('familyRole')
		this.mainHealthId = this.wx.getStorageSync('userInfo').memberNum
		this.idFaceBase64 = this.wx.getStorageSync('idFaceBase64').url
	},
	methods: {
		openError() {
			this.showToast('不允许进行拍摄将无法进行人脸验证')
		},
		next() {
			if (this.showCamera === true) {
				this.takePhoto()
			}
		},
		takePhoto() {
			const canvas = wx.createCanvasContext('myCanvas')
			const ctx = this.wx.createCameraContext()
			ctx.takePhoto({
				quality: 'high',
				success: res => {
					canvas.drawImage(res.tempImagePath, 0, 0)
					canvas.draw()
					setTimeout(() => {
						this.wx.canvasToTempFilePath({
							canvasId: 'myCanvas',
							success: res => {
								this.wx.getFileSystemManager().readFile({
									filePath: res.tempFilePath,
									encoding: 'base64',
									success: res => {
										this.faceBase64 = res.data
										this.faceDetection() //人脸检测
									}
								})
							},
							fail: res => {}
						})
					}, 800)
				},
				fail(res) {}
			})
		},
		async faceDetection() {
			await this.api.baiduApi
				.getAccessToken({
					grant_type: 'client_credentials',
					client_id: 'KGpj8RGpkLgtzCWn2NS3MEoq', //API Key
					client_secret: 'HR2GTZnA05bwZtwGMmg5OSNFFKZGG76L' //Secret Key
				})
				.then(data => {
					this.accessToken = data.access_token
				})
				.catch(err => {})

			this.api.baiduApi
				.faceDetection({
					image_type: 'BASE64',
					image: this.faceBase64,
					access_token: this.accessToken
				})
				.then(data => {
					if (data.error_code !== 0 || data.result.face_num > 1) {
						this.wx.showToast({
							title: '照片不符合要求，请重新拍摄哦',
							icon: 'none'
						})
						this.buttonText = '点击拍照'
						this.showCamera = true
					} else {
						if (this.$route.query.mode === 'oneFace') {
							this.oneFaceCompare() //单张人脸比对
						} else if (this.$route.query.mode === 'twoFace') {
							this.twoFacesCompare() //两张人脸比对
						}
					}
				})
				.catch(err => {})
		},

		oneFaceCompare() {
			this.api.tzApi
				.oneFaceCompare({
					idNumber: this.familyRole.idNumber,
					fileFiret: this.faceBase64
				})
				.then(data => {
					if (data.responseFlag === '1') {
						this.photoToken = data.data.token
						this.savePhoto()
					} else {
						this.wx.showToast({
							title: '照片不符合要求，请重新拍摄哦',
							icon: 'none'
						})
						this.buttonText = '点击拍照'
						this.showCamera = true
					}
				})
				.catch(() => {})
		},
		twoFacesCompare() {
			this.api.tzApi
				.twoFacesCompare({
					idNumber: this.familyRole.idNumber,
					fileFiret: this.faceBase64,
					fileSecond: this.idFaceBase64
				})
				.then(data => {
					if (data.responseFlag === '1') {
						this.photoToken = data.data.token
						this.savePhoto()
					} else {
						this.wx.showToast({
							title: '照片不符合要求，请重新拍摄哦',
							icon: 'none'
						})
						this.hideloading()
					}
				})
				.catch(() => {})
		},
		savePhoto() {
			//保存人脸底库照片
			this.api.tzApi
				.savePhoto({
					idNumber: this.familyRole.idNumber,
					name: this.familyRole.name,
					token: this.photoToken
				})
				.then(data => {
					if (data.responseFlag === '1') {
						this.insertFamily()
					} else {
						this.wx.showToast({
							title: '照片不符合要求，请重新拍摄哦',
							icon: 'none'
						})
						this.hideloading()
					}
				})
				.catch(() => {})
		},
		insertFamily() {
			//创建家庭角色
			let params = {
				mainHealthId: this.mainHealthId,
				familyRelation: this.familyRole.role,
				idNumber: this.familyRole.idNumber,
				name: this.familyRole.name,
				phone: this.familyRole.phone,
				token: this.photoToken
			}
			if (this.familyRole.parentIdNumber) {
				//未成年人
				params = Object.assign(params, {
					parentIdNumber: this.familyRole.parentIdNumber,
					parentName: this.familyRole.parentName
				})
			}
			this.api.tzApi
				.insertFamily(params)
				.then(data => {
					if (data.responseFlag === '1') {
						//领卡
					} else {
						this.wx.showToast({
							title: '照片不符合要求，请重新拍摄哦',
							icon: 'none'
						})
						this.hideloading()
					}
				})
				.catch(() => {})
		}
	}
}
</script>

<style lang="stylus">
	page
		width 100%
		height 100%
		overflow hidden
	.face-detection-wrap
		height 100%
		position relative
		.canvas
			position fixed
			width 100%
			top 0
			left 0
			height auto
			bottom 460px
		.camera
			position absolute
			cover()
			bottom 460px
			.detection-border
				width 450px
				height 450px
				border 2px solid themeColor
				position absolute
				top 50%
				left 50%
				transform translate(-50%,-50%)
		.camera-tools
			width 100%
			height 460px
			position absolute
			bottom 0
			.title
				line-height 120px
				font-size 34px
				text-align center
			.tips
				shadowBox()
				margin 0 mainMargin
				height 240px
				box-sizing border-box
				padding 40px
				.main
					font-size 30px
					line-height 48px
					margin-bottom 20px
				.sub
					font-size 28px
					color grayFontColor88
			.camera-btn
				position absolute
				bottom 0
				left 0
				right 0
				background-color themeColor
				line-height 100px
				height 100px
				text-align center
				color white
				font-size 36px


</style>
